﻿using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Markup;
using TcpTool;

namespace TestTcpToolDemo
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        TCPServer? server;

        //打开服务
        private async void Button_Click2(object sender, RoutedEventArgs e)
        {
            server = new TCPServer();

            //委托 +=、=都行 
            server.DataReceived += (client, data) =>
            {


            };

            //server.DataReceived = (client, data) =>
            //{

            //};

            server.ClientConnected += (client) =>
            {

            };

            server.IsOpenServer += (res) =>
            {

            };

            IPAddress iPAddress = IPAddress.Parse("192.168.0.155");
            await server.OpenServerAsync(iPAddress, 8011);
        }

        //关闭服务
        private void Button_Click22(object sender, RoutedEventArgs e)
        {
            server?.CloseServer();
        }

        List<TcpClient> clients = new();

        //获取到服务端中所有链接的客户端对象
        private void Button_Click3(object sender, RoutedEventArgs e)
        {
            clients = server?.GetClients()!;
            var clientIPs = server?.GetClientIPEndPoints()!;
        }

        //服务端发送数据
        private void Button_Click224(object sender, RoutedEventArgs e)
        {
            clients = server?.GetClients()!;
            byte[] data = Encoding.ASCII.GetBytes("start");
            server?.SendDataAsync(clients[0], data);
        }

        TCPClient? client;

        //客户端连接
        private async void Button_Click4(object sender, RoutedEventArgs e)
        {
            client = new TCPClient();
            IPAddress iPAddress = IPAddress.Parse("192.168.0.155");

            client.DataReceived += (data) =>
            {

            };

            //client.DataReceived = (data) =>
            //{

            //};

            client.IsClientConnect += (res) =>
            {

            };

            var res = await client.ConnectAsync(iPAddress, 8011);
        }

        //客户端断开连接
        private void Button_Click5(object sender, RoutedEventArgs e)
        {
            client?.Disconnect();
        }

        private void Button_Click6(object sender, RoutedEventArgs e)
        {
            clients = server?.GetClients()!;
            TcpClient clientToRemove = clients[0]; // 假设要删除第一个客户端
            server?.DisconnectClient(clientToRemove);
        }

        //客户端发送数据
        private void Button_Click7(object sender, RoutedEventArgs e)
        {
            var str = Encoding.ASCII.GetBytes("start");
            client?.SendDataAsync(str);
        }


    }
}